﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace MetaSharp.Transformation.Patterns
{
    class RangePattern<T> : Pattern where T : IComparable
    {
        public T Left { get; private set; }
        public T Right { get; private set; }
        public RangePattern(T left, T right)
            : base(PatternKind.Range)
        {
            if (left == null)
                throw new ArgumentNullException("left");
            if (right == null)
                throw new ArgumentNullException("right");
            if (left.CompareTo(right) > 0)
                throw new ArgumentException("Left must be less than right", "left");

            this.Left = left;
            this.Right = right;
        }

        public override PatternMatch Compile()
        {
            return s => Target(s, Left, Right);
        }

        private static async Task<IMatch> Target(IScope scope, T left, T right)
        {
            if (!scope.Stream.IsEmpty)
            {
                var next = scope.Stream.Next();
                var value = next.Current;
                if ((left == null && right == null) ||
                    (left != null && right != null) &&
                    (value is T) &&
                    (left.CompareTo(value) <= 0 && right.CompareTo(value) >= 0))
                {
                    return new Match(
                        value,
                        scope,
                        scope.SetStream(next));
                }
            }

            return await Transformation.Match.Fail(scope);
        }
    }
}
